#!/usr/bin/env php
<?php
require_once('bootstrap.php');
require_once('bulldoc/output_generator.php');
require_once('bulldoc/chm_generator.php');
require_once('getopt/getopt.php');

class docgenBuilder
{
  private $loader;

//---------------------------------------------------
  private function createBook($key)
  {
    $books=$this->loader->getBooks();
    if (!isset($books[$key])) {
      $bookDir=colesoApplication::getConfigVal('/bulldoc/source')."$key/";
      mkdir ($bookDir,0777);
      mkdir ($bookDir.'pages',0777);
      file_put_contents($bookDir.'toc.yml','');
      file_put_contents($bookDir.'book_data.yml',"title: $key\nauthor: Incognito\ncopyright: Me, 2008\nsite: www.mysite.ru");
      
      $bookshelfFile=colesoApplication::getConfigVal('/bulldoc/bookshelfConfig');
      file_put_contents($bookshelfFile,"\n$key:",FILE_APPEND);
      echo 'New book created';
    } else {
      echo 'This book allready exists';
    }
  }
//---------------------------------------------------
  protected function getBookshelfFile($parsedRequest)
  {
    if (isset($parsedRequest[0]['f'])) return $parsedRequest[0]['f'];
    if (file_exists('bulldoc')) return null;  //use autoconfig in bookLoader
    if (file_exists('bookshelf.yml')) return null;
    
    //we are in outside bulldoc dir and there is no bookshelf file in cwd
    //let's create new one (empty)
    file_put_contents('bookshelf.yml',"");
  }
//---------------------------------------------------
  public function run()
  {
    global $argc,$argv;
    if ($argc < 2 || in_array($argv[1], array('--help', '-help', '-h', '-?'))) {
      require (colesoApplication::getConfigVal('/bulldoc/systemTemplates').'help.tpl.phtml');
    } else {
      $parsedRequest=Console_Getopt::getopt($argv, 'f:c:');
      $bookshelfFile=$this->getBookshelfFile($parsedRequest);
      $this->loader = new bookLoader($bookshelfFile);
      
      if (isset($parsedRequest[0]['c'])) {
        $this->createBook($parsedRequest[0]['c']);
        return;
      } else {
        if (!isset($parsedRequest[1][0])) die('Error. Bookname should be specified.');
        $generator= new outputGenerator($this->loader->getBook($parsedRequest[1][0]));
        $generator->build();
      }
    }
  }
}

//=====================================================================================
$old = umask(0);
$builder=new docgenBuilder();
$builder->run();
echo "\n";
umask($old);
?>